<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-tile">
        {{$t('route.systemBackup')}}
        <i v-if="false" class="iconfont iconzhongyiicon_gaojing"></i>
      </div>
      <div class="left-wrapper"></div>
      <div class="right-wrapper"></div>
    </div>
    <el-scrollbar class="page-content">
      <div class="content-wrapper">
        <el-card>
          <basic-table
            :pageMethod="(params) => {
              params.search = searchValue;
              return $pandaApi.apiGetBackupsList(params).then(result => {
                db_migration_index = result.db_migration_index;
                backupRows = result.rows;
                return {
                  db_migration_index: db_migration_index,
                  rows: fuzzyQuery(result.rows, searchValue),
                  total: 1
                };
              });
            }"
          >
            <template #table-options="tableSlotData">
              <div class="table-left-options">
                <el-button type="primary" class="icon-button setting-button" style="width: auto;" @click="backupNow">
                  <i class="iconfont iconzhongyiicon_chuangjian" style="font-size: 12px; margin-right: 5px;"></i>
                  <span style="font-size: 12px;">{{$t('systemBack.backupNow')}}</span>
                </el-button>
                <el-button class="icon-button setting-button" style="width: auto;" @click="batchDelete(tableSlotData.table.selectRows)" :disabled="tableSlotData.table.selectRows.length <= 0">
                  <i class="el-icon-delete" style="font-size: 12px; margin-right: 5px;"></i>
                  <span style="font-size: 12px;">{{$t('common.BatchDelete')}}</span>
                </el-button>
                <el-dropdown style="margin-left: 10px;" @command="(cmd) => { switch(cmd) {
                  case 'recovery-by-lately':
                    recoveryByLately(tableSlotData.table.data[0]);
                    break;
                  case 'recovery-by-upload':
                    recoveryByUpload();
                    break;
                  case 'delete-all-loading':
                    deleteAll();
                    break;
                } }" :hide-on-click="false">
                  <el-button class="icon-button setting-button" style="width: auto;">
                    <span style="font-size: 12px;">{{$t('common.More')}}</span>
                    <i class="el-icon-arrow-down el-icon--right" style="font-size: 12px; margin-left: 5px;"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :disabled="recoveryByLatelyLoading" :command="'recovery-by-lately'">{{$t('systemSettings.RecoveryByLatelyTitle')}}<i v-if="recoveryByLatelyLoading" class="el-icon-loading" style="color: #333333; margin-left: 5px;"></i></el-dropdown-item>
                    <el-dropdown-item :disabled="recoveryByUploadLoading" :command="'recovery-by-upload'">{{$t('systemBack.uploadBackupAndRestore')}}<i v-if="recoveryByUploadLoading" class="el-icon-loading" style="color: #333333; margin-left: 5px;"></i></el-dropdown-item>
                    <el-dropdown-item :disabled="deleteAllLoading" :command="'delete-all-loading'">{{$t('systemBack.deleteAllBackup')}}<i v-if="deleteAllLoading" class="el-icon-loading" style="color: #333333; margin-left: 5px;"></i></el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <div class="table-right-options">
                <span style="display: flex; align-items: center; margin-right: 15px; font-size: 14px; color: #337DFF;"><span>{{$t('systemBack.databaseVersion')}}</span>{{ db_migration_index }}</span>
                <el-input :placeholder="$t('systemSettings.searchBackUp')" v-model="searchValue" @keyup.enter.native="tableSearchChange(tableSlotData)" style="width: 200px;" >
                </el-input>
                <el-button @click="tableSlotData.table.refresh" type="primary" style="margin-left: 10px;" >{{ $t('common.search') }}</el-button>
              </div>
            </template>
            <template #table-column="tableSlotData">
              <el-table-column type="selection" width="40" align="center"></el-table-column>
              <el-table-column
                prop="created_at"
                :label="$t('systemBack.backupTime')"
              ></el-table-column>
              <el-table-column
                prop="backup_name"
                :label="$t('systemBack.backupName')"
              >
              </el-table-column>
              <el-table-column
                prop="db_migration_index"
                :label="$t('systemBack.version')"
              >
              </el-table-column>
              <el-table-column
                prop="file_size"
                :label="$t('systemBack.backupSize')"
              >
                <template #default="props">
                  <span>{{ props.row.file_size }}KB</span>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('common.action')"
                width="200"
              >
                <template #default="props">
                  <link-button :content="$t('common.delete')" :size="10" :font-size="'12px'" style="margin-right: 15px;" @click="batchDelete([props.row])"/>
                  <link-button :content="$t('objectActive.recover')" :size="10" :font-size="'12px'" style="margin-right: 15px;" @click="recoveryByRow(props.row)" />
                  <link-button :content="$t('objectActive.download')" :size="10" :font-size="'12px'" style="margin-right: 15px;" @click="getDownloadUrl(props.row)" />
                </template>
              </el-table-column>
            </template>
            <template #others-elements="tableSlotData">
              <password-delete-dialog ref="PasswordDeleteDialog" :delete-method="(itemList) => {
                return $pandaApi.apiBatchDeleteBackup(itemList).then(() => {
                  tableSlotData.table.refresh();
                });
              }"></password-delete-dialog>
              <password-delete-dialog ref="RecoveryByUploadDialog" :delete-method="confirmManualRecover">
                <template #content>
                  <div class="upload-container">
                    <el-upload
                      :file-list="uploadBackupFileList"
                      :action="'1'"
                      ref="upload"
                      :on-success="() => {}"
                      :auto-upload="false"
                      :before-remove="() => { confirmRecoverFileList = [] }"
                      :http-request="uploadSectionFile"
                      accept=".sql"
                      :on-change="handleBackupUploadChange"
                    >
                      <el-button>{{$t('systemBack.selectFile')}}</el-button>
                    </el-upload>
                  </div>
                </template>
              </password-delete-dialog>
              <password-delete-dialog ref="RecoveryByRowsDialog" :delete-method="(itemList) => {
                return $pandaApi.apiRecoverFromBackup(itemList[0].backup_name).then((res) => {
                  tableSlotData.table.refresh();
                  return res;
                })
              }" />
              <backup-now-form-dialog ref="backupNow" @success="tableSlotData.table.refresh" />
            </template>
          </basic-table>
        </el-card>
      </div>
    </el-scrollbar>
  </div>
</template>
<script lang="ts">
import Vue from 'vue'
import BasicTable from '../../components/Basic/Table/BasicTable.vue';
import LinkButton from '../../components/Basic/Button/LinkButton.vue';
import PasswordDeleteDialog from '../resource/components/PasswordDeleteDialog.vue';
import backupNowFormDialog from './components/backupNowFormDialog.vue';
export default Vue.extend({
  components: {
    BasicTable,
    LinkButton,
    PasswordDeleteDialog,
    backupNowFormDialog
  },
  data() {
    return {
      searchValue: "",
      recoveryByLatelyLoading: false,
      recoveryByUploadLoading: false,
      deleteAllLoading: false,
      db_migration_index: "",
      backupRows: [],
      uploadBackupFileList: [],
      confirmRecoverFileList: [],
      confirmRecoverPassword: ""
    };
  },
  methods: {
    batchDelete(selectRows: Array<any>) {
      (this as any).$refs.PasswordDeleteDialog.init({
        title: (this as any).$t('systemSettings.BatchDeleteBackupTitle'),
        tip: (this as any).$t('systemSettings.batchDeleteBackupTip'),
        message: (this as any).$t('systemSettings.batchDeleteBackupMessage'),
        resourceList: selectRows
      });
    },
    recoveryByUpload() {
      (this as any).$refs.RecoveryByUploadDialog.init({
        title: (this as any).$t('systemSettings.BatchRecoveryByUploadTitle'),
        tip: (this as any).$t('systemSettings.batchRecoveryByUploadTip'),
        message: (this as any).$t('systemSettings.batchRecoveryByUploadMessage'),
        resourceList: []
      });
    },
    deleteAll() {
      (this as any).$refs.PasswordDeleteDialog.init({
        title: (this as any).$t('systemSettings.BatchDeleteBackupTitle'),
        tip: (this as any).$t('systemSettings.batchDeleteBackupTip'),
        message: (this as any).$t('systemSettings.batchDeleteBackupMessage'),
        resourceList: [{
          backup_name: 'all'
        }]
      });
    },
    getDownloadUrl(backup: any) {
      (this as any).$pandaApi.apiDownloadBackup(backup.backup_name).then((res: any) => {
        const blob = new Blob([res], { type: "text/plain;charset=utf-8" });
        const url = window.URL.createObjectURL(blob);
        const a: any = document.createElement("a");
        a.href = url;
        a.download = [backup.backup_name];
        a.click();
        window.URL.revokeObjectURL(url);
      });
    },
    recoveryByRow(row: any) {
      (this as any).$refs.RecoveryByRowsDialog.init({
        title: (this as any).$t('systemSettings.RecoveryByRowTitle'),
        tip: (this as any).$t('systemSettings.recoveryByRowTip'),
        message: (this as any).$t('systemSettings.recoveryByRowMessage'),
        resourceList: [row]
      });
    },
    recoveryByLately(row: any) {
      (this as any).$refs.RecoveryByRowsDialog.init({
        title: (this as any).$t('systemSettings.RecoveryByLatelyTitle'),
        tip: (this as any).$t('systemSettings.recoveryByLatelyTip'),
        message: (this as any).$t('systemSettings.recoveryByLatelyMessage'),
        resourceList: [row]
      });
    },
    uploadSectionFile(file: any) {
      (this as any).$pandaApi.apiRecoverFromFile(file.file.name, file.file)
        .then((response: any) => {
          (this as any).$refs.RecoveryByUploadDialog.handleClose();
          (this as any).uploadBackupFileList = [];
          (this as any).confirmRecoverFileList = [];
          if (response.error) {
            this.$message({
              message: (this as any)._(response.data.error_message),
              type: 'error'
            });
            return;
          }
          // this.getBackupsList()
          this.$message({
            message: (this as any)._('Database has been recovered from the upload file.'),
            type: 'success'
          });
        });
    },
    handleBackupUploadChange(file: any, fileList: any) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      // const isGz=file.raw.type==='application/gzip'
      if (!isLt10M) {
        (this as any).$message({
          message: (this as any)._('Upload file size can\'t exceed ') + 10 + 'MB!',
          type: 'warning'
        });
        fileList.splice(-1);
      }
      // if (!isGz) {
      //   this.$message({
      //     message: this._('Only support file with format gz to be uploaded.'),
      //     type: 'warning'
      //   })
      //   fileList.splice(-1)
      // }
      (this as any).uploadBackupFileList = fileList.slice(-1);
      (this as any).confirmRecoverFileList = (this as any).uploadBackupFileList;
      if ((this as any).uploadBackupFileList.length > 1) {
        (this as any).uploadBackupFileList = fileList.slice(-1);
        (this as any).confirmRecoverFileList = (this as any).uploadBackupFileList;
      }
    },
    confirmManualRecover() {
      return new Promise((resolve: any, reject: any) => {
        if ((this as any).uploadBackupFileList.length === 0) {
          this.$message({
            message: (this as any)._('Please select one file to recover.'),
            type: 'error'
          });
          reject({});
        } else {
          (this as any).$refs.RecoveryByUploadDialog.loading = true;
          (this as any).$refs.upload.submit();
        }
      });
    },
    fuzzyQuery(list: any, searchValue: any) {
      var arr = [];
      for (var i = 0; i < list.length; i++) {
        console.log(list[i]);
        if (list[i].backup_name.indexOf(searchValue) >= 0 || list[i].db_migration_index.indexOf(searchValue) >= 0 || searchValue === '') {
          arr.push(list[i]);
        }
      }
      return arr;
    },
    backupNow() {
      (this.$refs['backupNow'] as any).init();
    }
  }
})
</script>
<style lang="scss" scoped>
.page-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #EFF1F4;

  .page-header {
    height: 60px;
    background-color: #FFFFFF;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #D9D9D9;

    .page-tile {
      color: #031129;
      font-size: 16px;
      margin-left: 20px;

      .iconzhongyiicon_gaojing {
        margin-left: 5px;
      }
    }
  }

  .page-content {
    height: calc(100vh - 110px);
    overflow: hidden;
    flex-grow: 1;

    .content-wrapper {
      padding: 15px;
    }
  }
}

.table-left-options {
  display: flex;
}

.table-right-options {
  display: flex;

  .setting-button {
    margin-right: 10px;
  }
}

.delete-warning-icon {
  color: #FF931D;
  font-size: 20px;
  margin-right: 10px;

  &::before {
    font-size: 20px;
  }
}

.upload-container {
  padding-left: 80px;
  margin: 15px 0px;
  display: flex;
}
</style>
